#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
进程管理模块 - 用于调用外部exe进程
"""

import asyncio
import subprocess
import os
import sys
from typing import Dict, Any


class ProcessManager:
    """进程管理器"""
    
    def __init__(self):
        # 获取当前脚本所在目录
        if getattr(sys, 'frozen', False):
            # 如果是打包后的exe
            self.base_dir = os.path.dirname(sys.executable)
        else:
            # 如果是脚本运行
            self.base_dir = os.path.dirname(os.path.abspath(__file__))
        
        # 设置exe文件路径
        self.angle_recognition_exe = os.path.join(self.base_dir, "./tools/角标识别.exe")
        self.task_statistics_exe = os.path.join(self.base_dir, "./tools/任务统计.exe")
        
        print(f"📁 基础目录: {self.base_dir}")
        print(f"🔍 角标识别exe: {self.angle_recognition_exe}")
        print(f"📊 任务统计exe: {self.task_statistics_exe}")
    
    def check_exe_files(self) -> Dict[str, bool]:
        """检查exe文件是否存在"""
        return {
            'angle_recognition': os.path.exists(self.angle_recognition_exe),
            'task_statistics': os.path.exists(self.task_statistics_exe)
        }
    
    def get_exe_paths(self) -> Dict[str, str]:
        """获取exe文件路径"""
        return {
            'angle_recognition': self.angle_recognition_exe,
            'task_statistics': self.task_statistics_exe
        }
    
    async def run_angle_recognition(self) -> Dict[str, Any]:
        """运行角标识别进程"""
        try:
            if not os.path.exists(self.angle_recognition_exe):
                return {
                    'success': False,
                    'message': f'角标识别.exe文件不存在: {self.angle_recognition_exe}'
                }
            
            print(f"🚀 启动角标识别进程: {self.angle_recognition_exe}")
            
            # 异步执行进程
            process = await asyncio.create_subprocess_exec(
                self.angle_recognition_exe,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=self.base_dir
            )
            
            # 等待进程完成
            stdout, stderr = await process.communicate()
            
            if process.returncode == 0:
                output = stdout.decode('utf-8', errors='ignore')
                return {
                    'success': True,
                    'message': f'角标识别完成\n输出: {output}',
                    'output': output
                }
            else:
                error = stderr.decode('utf-8', errors='ignore')
                return {
                    'success': False,
                    'message': f'角标识别失败 (返回码: {process.returncode})\n错误: {error}',
                    'error': error
                }
                
        except Exception as e:
            return {
                'success': False,
                'message': f'启动角标识别进程时发生错误: {str(e)}'
            }
    
    async def run_task_statistics(self) -> Dict[str, Any]:
        """运行任务统计进程"""
        try:
            if not os.path.exists(self.task_statistics_exe):
                return {
                    'success': False,
                    'message': f'任务统计.exe文件不存在: {self.task_statistics_exe}'
                }
            
            print(f"🚀 启动任务统计进程: {self.task_statistics_exe}")
            
            # 异步执行进程
            process = await asyncio.create_subprocess_exec(
                self.task_statistics_exe,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=self.base_dir
            )
            
            # 等待进程完成
            stdout, stderr = await process.communicate()
            
            if process.returncode == 0:
                output = stdout.decode('utf-8', errors='ignore')
                return {
                    'success': True,
                    'message': f'任务统计完成\n输出: {output}',
                    'output': output
                }
            else:
                error = stderr.decode('utf-8', errors='ignore')
                return {
                    'success': False,
                    'message': f'任务统计失败 (返回码: {process.returncode})\n错误: {error}',
                    'error': error
                }
                
        except Exception as e:
            return {
                'success': False,
                'message': f'启动任务统计进程时发生错误: {str(e)}'
            }


# 测试代码
if __name__ == "__main__":
    async def test():
        manager = ProcessManager()
        
        # 检查文件
        exe_status = manager.check_exe_files()
        exe_paths = manager.get_exe_paths()
        
        print(f"角标识别exe存在: {exe_status['angle_recognition']}")
        print(f"任务统计exe存在: {exe_status['task_statistics']}")
        print(f"角标识别路径: {exe_paths['angle_recognition']}")
        print(f"任务统计路径: {exe_paths['task_statistics']}")
        
        # 测试角标识别
        if exe_status['angle_recognition']:
            print("\n测试角标识别...")
            result = await manager.run_angle_recognition()
            print(f"结果: {result}")
        
        # 测试任务统计
        if exe_status['task_statistics']:
            print("\n测试任务统计...")
            result = await manager.run_task_statistics()
            print(f"结果: {result}")
    
    asyncio.run(test())
